<template>
  <div class="app-container">

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="(item, index) in tabList" :key="index" :label="item.dictLabel" :name="item.dictValue">

        <el-table v-loading="loading" max-height="400px" :data="datadetail[item.dictValue].datalist" border
                  :header-cell-style="{background:'#F5F7FA'}">
          <el-table-column label="OTA平台订单车型" align="center" prop="vehicleName">
          </el-table-column>

          <el-table-column label="对应平台车型" align="center" prop="modelId">
            <template v-slot="scope">
              <el-select
                v-model="scope.row.modelId"
                filterable clearable
                placeholder="请选择">

                <el-option
                  v-for="item in options"
                  :key="item.configurationId"
                  :label="`${item.modelInfo} / ${item.modelName}`"
                  :value="item.modelId">
                </el-option>
              </el-select>

            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="datadetail[item.dictValue].total>0"
          :total="datadetail[item.dictValue].total"
          :page.sync="datadetail[item.dictValue].pageNum"
          :limit.sync="datadetail[item.dictValue].pageSize"
          @pagination="getList(null)"
        />

      </el-tab-pane>
    </el-tabs>

    <div class="bottom-layout">
      <el-button @click="cancel">关 闭</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>

  </div>
</template>

<script>

import {listByAvailable, otamodellist, otamodelsave} from "@/api/ota/ctrip";

export default {
  data() {
    return {
      loading: false,
      datadetail: {},
      tabList: [
      //   {
      //   name: '携程'
      // }, {
      //   name: '租租车'
      // }, {
      //   name: '哈啰'
      // }, {
      //   name: '悟空'
      // },
      ],
      options: [],
      activeName:null,
    };
  },
  computed: {
    // activeName: {
    //   get() {
    //     return this.tabList[0].name
    //   },
    //   set(newVal) {
    //     return newVal
    //   }
    // }
  },

  async mounted() {
    this.tabList = await this.getDict();

    for (const tab of this.tabList) {
      tab.dictValue = String(tab.dictValue)
      this.datadetail[tab.dictValue] = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        datalist: [],
        first: true,
        selList: []
      }
    }
    this.activeName = this.tabList[0].dictValue

    await this.getList(this.activeName)
    await this.getModelData();
  },

  methods: {
    getDict(){

      return new Promise(resolve => {
        this.getDicts("ota_order_resource").then(response => {
          resolve(response.data)
        });
      })

    },

    getList(name) {
      this.loading = true;
      let _this = this

      let requestName = name || _this.activeName

      _this.datadetail[requestName].selList = _this.datadetail[requestName].selList.concat(_this.datadetail[requestName].datalist)

      _this.datadetail[requestName].selList = _this.removeRepeat(_this.datadetail[requestName].selList, 'vehicleName')


      otamodellist(
        {
          orderSourceCode: requestName,
          pageNum: _this.datadetail[requestName].pageNum,
          pageSize: _this.datadetail[requestName].pageSize,
        }
      ).then(res => {
        _this.datadetail[requestName].datalist = res.rows
        _this.datadetail[requestName].total = res.total
        _this.datadetail[requestName].first = false

        for (const item of _this.datadetail[requestName].datalist) {
          for (const itemElement of _this.datadetail[requestName].selList) {
            if (item.vehicleName === itemElement.vehicleName) {
              item.modelId = itemElement.modelId
              break
            }
          }
        }


        this.loading = false;
      }).catch(e => {
        this.loading = false;
      })

    },

    getModelData() {
      listByAvailable().then(res => {
        this.options = res.rows
      })
    },

    handleClick(tab, event) {
      this.activeName = this.tabList[tab.index].dictValue
      if (tab.index > 0 && this.datadetail[this.tabList[tab.index].dictValue].first) {
        this.getList(this.activeName)
      }
    },

    cancel() {
      this.$emit('cancel')
    },

    removeRepeat(arr, name) {   //arr是传入的对象数组，name是根据去重的key
      let hash={}   //创建一个空对象，来保存需要的index
      return arr.reduce((acc, cru,index)=> {  //reduce()方法，功能是累加，第一个参数是累加起来的值，cru第二个参数，是数组遍历的其中一个元素，第三个参数是遍历的当前元素的索引
        if (!hash[cru[name]]) {  //判断hash[cru[name]]是否含有值，如果没有，则用hash[cru[name]]保存当前遍历元素的索引
          hash[cru[name]]={index:index}
          acc.push(cru)
        }else{//如果有值,说明重复，则通过保存的hash[cru[name]]去重
          acc.splice(hash[cru[name]]['index'],1,cru)
        }
        return acc;
      }, []);
    },

    confirm() {
      this.loading = true;

      let _this = this

      for (const key in this.datadetail) {
        this.datadetail[key].selList =
          this.datadetail[key].selList.concat(this.datadetail[key].datalist)

        this.datadetail[key].selList = _this.removeRepeat(this.datadetail[key].selList, 'vehicleName')
      }

      const list = []
      for (const key in this.datadetail) {
        if (this.datadetail[key].selList !== null && this.datadetail[key].selList.length > 0) {
          this.datadetail[key].selList.forEach(i => {
            let item = {
              id: i.id,
              vehicleId: i.vehicleId,
              orderSource: i.orderSource,
              orderSourceCode: i.orderSourceCode,
              vehicleName: i.vehicleName,
              modelId: i.modelId
            }
            list.push(item)
          })
        }
      }

      otamodelsave(list).then(res => {
        this.$message({
          message: '同步成功',
          type: 'success'
        });
        this.loading = false;
        this.$emit('success')
      }).catch(e => {
        this.loading = false;
      })

    }
  }
};
</script>

<style scoped>

.app-container {
  display: flex;
  flex-direction: column;
}


.bottom-layout {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin: 30px 0 0;
}

</style>
